﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using qna.Business;
using qna.Controls;
using System.Diagnostics;
using qna.Services;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Drawing;



namespace qna.pages
{
    public partial class SearchResults : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["searchString"] != null)
            {
                int results = LoadQuestions(Request.QueryString["searchString"]);
                if (results > 1)
                {
                    ResultSearch.InnerText = results + " Matches found for '" + Request.QueryString["searchString"] + "'";
                }
                else
                {
                    ResultSearch.InnerText = results + " Match found for '" + Request.QueryString["searchString"] + "'";
                }

            }
            else
            {
                Response.StatusCode = 404;
                ResultSearch.InnerText = "Oops! Something went wrong!";
            }
        }

        private int LoadQuestions(string searchText)
        {
            SearchService sc = new SearchService();
            int count = 0;

            IList<Business.Question> QuestionList = sc.Search(searchText);
            count = QuestionList.Count;

            foreach (Business.Question q in QuestionList)
            {
                QuestionControl qc = (QuestionControl)LoadControl("~/Controls/QuestionControl.ascx");
                qc.Question = q;
                qc.txtToSearch = searchText;

                //if (qc.Question.Content.Contains(searchText))
                //{
                //    string qContent = qc.Question.Content;
                //    qContent = Regex.Replace(qContent, searchText, "<b>"+searchText+"</b>", RegexOptions.IgnoreCase);
                //    qc.Question.Content = qContent;
                    
                //}
                SearchList.Controls.Add(qc);
            }

            return count;

        }
    }
}